import { _decorator, Component, instantiate, log, Node, NodePool, Prefab, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PipeLayer')
export class PipeLayer extends Component {
    // 管道节点预制资源
    @property(Prefab)
    pipePrefab: Prefab = null;
    // pipe对象池
    private _pipePool: NodePool;
    // pipe节点集合
    private _pipeList: Node[] = [];
    // 管道是否移动中
    private _pipeIsRunning = false;
    // 管道移动速度，单位px/s 
    private _pipeMoveSpeed = -400;
    // 每对管道之间的间距，单位px
    private _pipeSpacing = 500;
    // 管道回收X轴位置
    private _recylceX = 0;

    /**
     * 初始化
     */
    start() {
        // 创建管道障碍物对象池
        this._pipePool = new NodePool();
        for (let i = 0; i < 3; ++i) {
            // 实例化节点
            let pipe = instantiate(this.pipePrefab);
            // 放入对象池
            this._pipePool.put(pipe);
        };
    }

    /**
     * 每一帧渲染前执行
     */
    update(deltaTime: number) {
        if (!this._pipeIsRunning) return;
        // 实时更新管道位置
        for (let i = 0; i < this.node.children.length; i++) {
            let posX = this.node.children[i].getPosition().x + this._pipeMoveSpeed * deltaTime;
            let posY = this.node.children[i].getPosition().y;
            this.node.children[i].setPosition(posX, posY);
            // 超出屏幕显示范围了，回收此管道
            if (posX < this._recylceX) {
                this.recyclePipe(this.node.children[i])
            }
        }
    }

    /**
     * 重置
     */
    public reset() {
        // 定时生成管道
        this.unschedule(this.spawnPipe);
        this._pipeList = [];
        this._pipeIsRunning = false;
    }

    /**
     * 获取下个未通过的水管
     */
    public getNextPipe() {
        return this._pipeList.shift();
    }

    /**
     * 定时生成管道，并开始移动
     */
    public startSpawn() {
        // 初始化管道根节点
        this.node.removeAllChildren();
        // 生成一组管道
        this.spawnPipe();
        // 定时生成管道
        let spawnInterval = Math.abs(this._pipeSpacing / this._pipeMoveSpeed);
        this.schedule(this.spawnPipe, spawnInterval);
        // 开始移动
        this._pipeIsRunning = true;
    }

    /**
     * 生成管道
     */
    spawnPipe() {
        let pipeGroup: Node = null;
        if (this._pipePool.size() > 0) {
            pipeGroup = this._pipePool.get();
        } else {
            pipeGroup = instantiate(this.pipePrefab);
        };
        this.node.addChild(pipeGroup);
        this.initPosition(pipeGroup);
        pipeGroup.active = true;
        this._pipeList.push(pipeGroup);
        log("_pipeList:",this._pipeList.length)
    }

    /**
     * 初始化管道位置
     */
    initPosition(pipeGroup: Node) {
        const visibleSize = this.node.getComponent(UITransform); 
        const pipeSize = pipeGroup.getComponent(UITransform); 
        // 设置管道节点初始位置
        let posX = (visibleSize.width / 2) + this._pipeSpacing;
        let posY = this.generateRandom(-visibleSize.height / 4, visibleSize.height / 4);
        pipeGroup.setPosition(posX, posY);
        // 管道超出屏幕X轴显示，回收范围
        this._recylceX = - (visibleSize.width / 2) - pipeSize.width;
    }

    /**
     * 回收管道
     */
    recyclePipe(pipeGroup: Node) {
        pipeGroup.active = false;
        this._pipePool.put(pipeGroup);
    }

    /**
	 * 生成范围随机数 
	 */
	generateRandom(min:number, max:number):number {
		let Range = max - min;
		let Rand = Math.random();
		return (min + Math.round(Rand * Range));
	}
}
